Popular Searches
Popular Course Categories
Popular Courses

Using FileReader and FileWriter

Using FileReader and FileWriter

File Handling, I/O Streams, and Serialization

Using FileReader and FileWriter in Java

Course: Core Java Training

Topic: Using FileReader and FileWriter

Course Link: Core Java Training Course – JustAcademy

Demo Link: Register for a Free Course Demo

Website: JustAcademy Official Website


1. Introduction to FileReader and FileWriter

Java provides several classes for reading and writing data to files. FileReader and FileWriter are character-based I/O classes used to read and write text files. They belong to the java.io package.

These classes are useful when working with text-based data such as notes, configuration files, reports, logs, and simple text documents.

  • FileReader: Reads character data from a file.
  • FileWriter: Writes character data to a file.
  • BufferedReader: Can improve reading efficiency and provides convenient line-by-line reading.
  • BufferedWriter: Can improve writing efficiency and provides convenient methods for writing text.

2. What Is FileReader?

FileReader is a Java class used to read text from a file as characters. It is appropriate for text files when the file's character encoding is handled correctly.

Syntax

FileReader reader = new FileReader("input.txt");

The statement creates a FileReader object that opens the specified file for reading. If the file does not exist or cannot be opened, Java may throw an IOException.

Important FileReader Methods

Method Description
read() Reads one character and returns its integer value, or -1 when the end of the file is reached.
read(char[] cbuf) Reads characters into a character array and returns the number of characters read, or -1 at the end of the file.
close() Closes the reader and releases associated resources.

3. What Is FileWriter?

FileWriter is a Java class used to write character data to a text file. It can create a new file if the target file does not exist and the required directory and permissions are available.

Syntax

FileWriter writer = new FileWriter("output.txt");

By default, opening a file this way overwrites its existing contents. To append new text instead, use the append-enabled constructor.

Important FileWriter Methods

Method Description
write(String str) Writes a string to the file.
write(int c) Writes a character represented by the supplied integer value.
write(char[] cbuf) Writes the characters contained in an array.
append(CharSequence csq) Appends character data to the writer's output.
flush() Forces buffered output to be written to the underlying destination where possible.
close() Closes the writer and releases associated resources.

4. Difference Between FileReader and FileWriter

Feature FileReader FileWriter
Purpose Reads text from a file. Writes text to a file.
Operation Input operation. Output operation.
Direction File to Java application. Java application to file.
Common method read() write()
File handling Requires a readable source file. Can create a destination file when permitted.
Existing content Reads existing content. Normally overwrites content unless append mode is enabled.

5. Reading a File Using FileReader

The following example demonstrates how to read a text file character by character.

Example 1: Reading a Text File

import java.io.FileReader;
import java.io.IOException;

public class FileReaderExample {
    public static void main(String[] args) {
        try (FileReader reader = new FileReader("input.txt")) {
            int character;

            while ((character = reader.read()) != -1) {
                System.out.print((char) character);
            }

        } catch (IOException e) {
            System.out.println("Error reading file: " + e.getMessage());
        }
    }
}

Explanation

  1. Import FileReader and IOException.
  2. Create a reader for input.txt.
  3. Call read() repeatedly to obtain characters.
  4. Continue until read() returns -1, indicating the end of the file.
  5. Convert each returned character value to char and print it.
  6. Use try-with-resources to close the reader automatically.

Sample Input File

Welcome to Java.
File handling is easy to learn.

Output

Welcome to Java.
File handling is easy to learn.

6. Reading Multiple Characters at Once

Reading one character at a time is simple, but reading a group of characters into an array can reduce the number of read operations.

Example 2: Reading with a Character Array

import java.io.FileReader;
import java.io.IOException;

public class ReadCharacterArray {
    public static void main(String[] args) {
        try (FileReader reader = new FileReader("input.txt")) {
            char[] buffer = new char[1024];
            int count;

            while ((count = reader.read(buffer)) != -1) {
                System.out.print(new String(buffer, 0, count));
            }

        } catch (IOException e) {
            System.out.println("Unable to read file: " + e.getMessage());
        }
    }
}

Explanation

  • A character array of size 1024 is created as a temporary buffer.
  • The read(buffer) method fills the buffer with available characters.
  • The returned count indicates how many characters were actually read.
  • new String(buffer, 0, count) converts only the valid characters into a string.
  • The loop stops when the end of the file is reached.

7. Writing to a File Using FileWriter

The following example demonstrates writing text to a file.

Example 3: Writing Text to a File

import java.io.FileWriter;
import java.io.IOException;

public class FileWriterExample {
    public static void main(String[] args) {
        try (FileWriter writer = new FileWriter("output.txt")) {
            writer.write("Welcome to Core Java!");
            writer.write(System.lineSeparator());
            writer.write("Learning file handling with FileWriter.");

            System.out.println("Data written successfully.");

        } catch (IOException e) {
            System.out.println("Error writing file: " + e.getMessage());
        }
    }
}

Explanation

  1. Import the required I/O classes.
  2. Create a FileWriter object for output.txt.
  3. Use write() to write text to the file.
  4. Use System.lineSeparator() to insert a platform-appropriate line separator.
  5. Close the writer automatically using try-with-resources.

Output in the Console

Data written successfully.

Content of output.txt

Welcome to Core Java!
Learning file handling with FileWriter.

Important: Opening FileWriter in its default mode truncates an existing file. Use append mode if you need to preserve existing content.

8. Appending Data Using FileWriter

Appending means adding new content at the end of a file without deleting its existing content. Java supports this through the two-argument constructor.

Syntax

FileWriter writer = new FileWriter("output.txt", true);

The second argument, true, enables append mode.

Example 4: Appending Text

import java.io.FileWriter;
import java.io.IOException;

public class AppendFileExample {
    public static void main(String[] args) {
        try (FileWriter writer = new FileWriter("output.txt", true)) {
            writer.write(System.lineSeparator());
            writer.write("This line has been appended.");

            System.out.println("Text appended successfully.");

        } catch (IOException e) {
            System.out.println("Error appending text: " + e.getMessage());
        }
    }
}

Expected Result

The new sentence is added to the end of output.txt, while the existing contents remain unchanged.

9. Reading and Writing Files Together

A common file-handling task is reading content from one file and copying it into another file. The following example uses FileReader and FileWriter together.

Example 5: Copying a Text File

import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;

public class CopyTextFile {
    public static void main(String[] args) {
        try (
            FileReader reader = new FileReader("source.txt");
            FileWriter writer = new FileWriter("destination.txt")
        ) {
            char[] buffer = new char[1024];
            int count;

            while ((count = reader.read(buffer)) != -1) {
                writer.write(buffer, 0, count);
            }

            System.out.println("File copied successfully.");

        } catch (IOException e) {
            System.out.println("File operation failed: " + e.getMessage());
        }
    }
}

How It Works

  • source.txt contains the original text.
  • destination.txt is created if necessary or overwritten if it already exists.
  • The reader loads a chunk of characters into the buffer.
  • The writer writes only the number of characters returned by the reader.
  • The process continues until the entire file has been copied.

Note: This example is intended for text files. For images, PDFs, audio, and other binary files, use byte-based streams such as FileInputStream and FileOutputStream.

10. Using FileReader and FileWriter with try-with-resources

File operations use system resources. If a reader or writer is not closed properly, resources may remain occupied longer than necessary. Java's try-with-resources statement closes resources automatically.

Example 6: Safe File Writing

import java.io.FileWriter;
import java.io.IOException;

public class SafeFileWriting {
    public static void main(String[] args) {
        try (FileWriter writer = new FileWriter("message.txt")) {
            writer.write("This file is written safely.");

        } catch (IOException e) {
            System.out.println("I/O error: " + e.getMessage());
        }
    }
}

Advantages

  • Automatically closes resources.
  • Reduces the risk of resource leaks.
  • Makes the code easier to read and maintain.
  • Handles cleanup even if an exception occurs inside the try block.

11. Character Encoding Considerations

Character encoding determines how text characters are converted into bytes and how those bytes are interpreted. The traditional FileReader(String) and FileWriter(String) constructors use the JVM's default charset. If the file uses a different encoding, some characters may display incorrectly.

For predictable encoding, Java provides constructors that accept a Charset. For example, UTF-8 is widely used for text files.

Example 7: Reading and Writing with UTF-8

import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.nio.charset.StandardCharsets;

public class Utf8FileExample {
    public static void main(String[] args) {
        try (
            FileWriter writer = new FileWriter(
                "utf8.txt", StandardCharsets.UTF_8
            )
        ) {
            writer.write("Hello, Java! नमस्ते");

        } catch (IOException e) {
            System.out.println("Writing failed: " + e.getMessage());
        }

        try (
            FileReader reader = new FileReader(
                "utf8.txt", StandardCharsets.UTF_8
            )
        ) {
            int ch;

            while ((ch = reader.read()) != -1) {
                System.out.print((char) ch);
            }

        } catch (IOException e) {
            System.out.println("Reading failed: " + e.getMessage());
        }
    }
}

Compatibility note: The charset-aware constructors shown above are available in modern Java versions, including Java 11 and later. Use an appropriate alternative if working with an older Java version.

12. Common Errors and Troubleshooting

Error or Issue Possible Cause Solution
FileNotFoundException The source file does not exist or the path is incorrect. Check the filename, directory, and working directory.
IOException A file operation failed. Check permissions, file availability, and the exception message.
Existing content disappears FileWriter opened the file in overwrite mode. Use new FileWriter("file.txt", true) to append.
Special characters appear incorrectly The file and application use different character encodings. Specify the same charset when reading and writing.
Output appears incomplete Data may not have been flushed or the writer may not have been closed. Use try-with-resources or call flush() when appropriate.
Wrong file is accessed A relative path is resolved from an unexpected working directory. Verify the program's working directory or use a correct path.

13. Best Practices for FileReader and FileWriter

  • Use try-with-resources to close files automatically.
  • Handle file-related exceptions with meaningful error messages.
  • Use append mode when existing content must be preserved.
  • Specify an explicit charset such as UTF-8 when consistent encoding matters.
  • Use character buffers or buffered readers and writers for efficient text processing.
  • Validate file paths and permissions before performing file operations.
  • Avoid using character streams for binary data.
  • Test programs with empty files, large files, missing files, and non-English text.
  • Do not ignore exceptions silently, particularly in production applications.

14. FileReader vs BufferedReader

Feature FileReader BufferedReader
Primary purpose Reads characters from a file. Reads text efficiently through buffering.
Line-by-line reading Does not provide a readLine() method. Provides readLine().
Typical usage Basic character reading. Reading text files line by line.
Combination Can be wrapped in BufferedReader. Often created as new BufferedReader(new FileReader("input.txt")).

15. FileWriter vs BufferedWriter

Feature FileWriter BufferedWriter
Purpose Writes characters to a file. Buffers character output to improve efficiency.
Line separator Can write System.lineSeparator(). Provides the convenient newLine() method.
Performance May perform more underlying writes. Can reduce the number of underlying write operations.
Combination Can be wrapped in BufferedWriter. Commonly used for large text output.

16. Practical Example: Saving Student Details

This program demonstrates how to save basic student information in a text file.

import java.io.FileWriter;
import java.io.IOException;

public class StudentDetails {
    public static void main(String[] args) {
        String name = "Rahul";
        int rollNumber = 101;
        String course = "Core Java";

        try (FileWriter writer = new FileWriter("student.txt")) {
            writer.write("Student Name: " + name);
            writer.write(System.lineSeparator());
            writer.write("Roll Number: " + rollNumber);
            writer.write(System.lineSeparator());
            writer.write("Course: " + course);

            System.out.println("Student details saved.");

        } catch (IOException e) {
            System.out.println("Unable to save details: " + e.getMessage());
        }
    }
}

Expected File Content

Student Name: Rahul
Roll Number: 101
Course: Core Java

Practical Applications

  • Saving student records in a simple text format.
  • Writing application logs.
  • Generating basic text reports.
  • Storing small configuration files.
  • Creating and updating text-based data exports.

17. Practice Exercises

  1. Create a file named aboutme.txt and write five lines about yourself using FileWriter.
  2. Read the contents of aboutme.txt using FileReader and display them in the console.
  3. Write a program that appends a new sentence to an existing text file.
  4. Copy the contents of one text file into another using a character array.
  5. Write student name, roll number, and marks to a file.
  6. Read a UTF-8 text file containing English and Hindi characters.
  7. Modify a writing program to handle a missing directory or a file access error gracefully.

18. Interview Questions and Answers

Q1. What is FileReader in Java?

Answer: FileReader is a character stream class used to read text from files.

Q2. What is FileWriter in Java?

Answer: FileWriter is a character stream class used to write text to files.

Q3. Which package contains FileReader and FileWriter?

Answer: Both classes belong to the java.io package.

Q4. What does read() return at the end of a file?

Answer: It returns -1 when no more characters are available.

Q5. Does FileWriter overwrite existing file content?

Answer: Yes. Its default file-opening mode truncates existing content. Append mode can be enabled with the appropriate constructor.

Q6. How can we append text to a file?

Answer: Use new FileWriter("file.txt", true).

Q7. Why should we close a reader or writer?

Answer: Closing releases associated resources and ensures pending output is finalized. Try-with-resources automates this process.

Q8. What is the difference between character streams and byte streams?

Answer: Character streams process text characters, while byte streams process raw bytes and are suitable for binary data.

Q9. Can FileReader read a PDF file correctly?

Answer: Not as a general PDF reader. PDFs use a structured binary format, so a PDF-specific library is appropriate.

Q10. How can we specify UTF-8 while reading a file?

Answer: In modern Java, use a charset-aware constructor such as new FileReader("input.txt", StandardCharsets.UTF_8).

19. Quick Revision

  • FileReader reads text files character by character or into character arrays.
  • FileWriter writes character data to text files.
  • Both classes belong to java.io.
  • read() returns -1 at the end of the file.
  • The default FileWriter mode overwrites existing contents.
  • Use append mode to preserve existing content and add new text.
  • Use try-with-resources for automatic resource management.
  • Choose a consistent charset, such as UTF-8, when required.
  • Use byte streams for binary files.
  • Buffered character streams are useful for efficient text processing.

20. Conclusion

FileReader and FileWriter are fundamental Java classes for text file handling. FileReader enables applications to read character data, while FileWriter allows applications to create, overwrite, or append text files. Understanding file paths, exception handling, character encoding, append mode, and automatic resource management helps developers write reliable file-processing programs.

Practice these examples by creating your own text files, reading their contents, writing new data, and copying files. These skills provide a foundation for more advanced Java I/O concepts, including BufferedReader, BufferedWriter, FileInputStream, FileOutputStream, and the NIO file API.


Learn Core Java with JustAcademy

Explore the course to strengthen your Java programming and file-handling skills.

Explore Core Java Training

Register for a Course Demo

Visit JustAcademy

Previous Next
whatsapp